import { ElMessage } from "element-plus"
import { Directive } from "vue"
/**
 * 原生copy方法
 */
const copyText = (text: string): boolean => {
  const textarea = document.createElement("textarea")
  textarea.value = text
  document.body.appendChild(textarea)
  textarea.select()
  const successful = document.execCommand("copy")
  if (successful) {
    ElMessage.success("复制成功")
  } else {
    ElMessage.error("复制失败")
  }
  document.body.removeChild(textarea)
  return successful
}
export const copy: Directive = {
  mounted(el, binding) {
    el.addEventListener("click", () => {
      if (binding.value) {
        const text = typeof binding.value === "string" ? binding.value : binding.value.text
        copyText(text)
      }
    })
  }
}
